package com.crawler.parser;

import java.util.List;
import java.util.Map;

import com.crawler.entity.CrawlerLog;
import com.crawler.pojo.Constant;
import com.crawler.pojo.PageType;
import com.google.common.collect.Maps;

public class ParserKit{
	
	public static final Map<PageType, Parser> parserFactory = Maps.newHashMap();
	
	static{
		parserFactory.put(PageType.PAGE_FIRSTLOGIN, new LoginPageParser());
		parserFactory.put(PageType.PAGE_ORDER, new OrderPageParser());
		parserFactory.put(PageType.PAGE_ORDERDETIAL, new OrderDetialPageParser());
		parserFactory.put(PageType.PAGE_USERINFO, new UserInfoPageParser());
	}
	
	public static String parseText(final PageType pageType,final String html){
		String result = "";
		try {
			result = parserFactory.get(pageType).parseText(html);
		} catch (Exception e) {
			CrawlerLog.me.save(Constant.解析,pageType,Constant.FAILURE,getExceptionMsg(e),html);
		}
		return result;
	}
	
	public static String parseText(final PageType pageType,final String type,final String html){
		String result = "";
		try {
			result = parserFactory.get(pageType).parseText(type, html);
		} catch (Exception e) {
			CrawlerLog.me.save(Constant.解析,pageType,Constant.FAILURE,getExceptionMsg(e),html);
		}
		return result;
	}
	
	public static Map<String, Object> parseMap(final PageType pageType,final String html) {
		Map<String, Object> resultMap = null;
		try {
			resultMap = parserFactory.get(pageType).parseMap(html);
		} catch (Exception e) {
			CrawlerLog.me.save(Constant.解析,pageType,Constant.FAILURE,getExceptionMsg(e),html);
		}
		return resultMap;
	}

	public static List<Map<String, Object>> parseListMap(final PageType pageType,final String html) {
		List<Map<String, Object>> relustList = null;
		try {
			relustList = parserFactory.get(pageType).parseListMap(html);
		} catch (Exception e) {
			CrawlerLog.me.save(Constant.解析,pageType,Constant.FAILURE,getExceptionMsg(e),html);
		}
		return relustList;
	}
	
	public static List<String> parseList(final PageType pageType,final String html) {
		List<String> relustList = null;
		try {
			relustList = parserFactory.get(pageType).parseList(html);
		} catch (Exception e) {
			CrawlerLog.me.save(Constant.解析,pageType,Constant.FAILURE,getExceptionMsg(e),html);
		}
		return relustList;
	}
	
	public static String getExceptionMsg(Exception e) {
		String msg = e.getMessage();
		if(msg.length()>500){
			msg.substring(0, 500);
		}
		return msg;
	}
	
}
